#include <workflow/WFFacilities.h>
/* #include <workflow/HttpMessage.h> */
#include <workflow/HttpUtil.h>
/* #include <workflow/WFTaskFactory.h> */
#include <signal.h>

#include <iostream>

using std::cout;
using std::cerr;

static WFFacilities::WaitGroup waitGroup(1);
void handle(int signum){
    cout << "/ndone\n";
    waitGroup.done();
}

void httpCallback(WFHttpTask *httpTask){
    cout << "callback is called\n";

    protocol::HttpRequest *req = httpTask->get_req();
    protocol::HttpResponse *resp = httpTask->get_resp();

    int state = httpTask->get_state();
    int error = httpTask->get_error();

    switch(state){
    case WFT_STATE_SYS_ERROR:
        cerr << "system error: " << strerror(error) << "\n";
        break;
    case WFT_STATE_DNS_ERROR:
        cerr << "DNS error: " << strerror(error) << "\n";
        break;
    case WFT_STATE_SSL_ERROR:
        cerr << "SSL error: " << strerror(error) << "\n";
        break;
    case WFT_STATE_TASK_ERROR:
        cerr << "Task error: " << strerror(error) << "\n";
        break;
    case WFT_STATE_SUCCESS:
        break;
    }
    if(state != WFT_STATE_SUCCESS){
        cerr << "Failed. Please Press Ctrl-C to exit\n";
        return;
    }

    cerr << "method = " << req->get_method()
        << "version = " << req->get_http_version()
        << "path&query = " << req->get_request_uri() << "\n";

    std::string name;
    std::string value;
    protocol::HttpHeaderCursor req_cursor(req);
    while(req_cursor.next(name, value)){
        cerr << "name = " << name << " value = " << value << "\n";
    }

    protocol::HttpHeaderCursor resp_cursor(resp);
    while(resp_cursor.next(name, value)){
        cerr << "name = " << name << " value = " << value << "\n";
    }

    const void *body;
    size_t body_len;
    resp->get_parsed_body(&body, &body_len);
    cerr << static_cast<const char *>(body) << "\n";

    cout << "callback finish\n";
}

int main(){
    signal(SIGINT, handle);

    WFHttpTask *httpTask = WFTaskFactory::create_http_task(
        "http://www.taobao.com",
        10,
        10,
        httpCallback
        );

    protocol::HttpRequest *req = httpTask->get_req();
    req->set_method("POST");
    req->set_request_uri("/search?q=12600kf");
    req->add_header_pair("MyName", "Workflow");

    httpTask->start();

    waitGroup.wait();
    cout << "finish!\n";

    return 0;
}
